package com.ikas.ai.server.module.steady.service;

import cn.hutool.core.lang.Assert;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ikas.ai.model.KafkaMeteData;
import com.ikas.ai.server.module.steady.dao.SteadyStateMeteMapper;
import com.ikas.ai.server.module.steady.enums.SteadyExecStatusEnum;
import com.ikas.ai.server.module.steady.model.po.SteadyStateMete;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.sql.Timestamp;
import java.util.List;

/**
 * <p>
 * 稳态测点表 服务实现类
 * </p>
 *
 * @author wuyf
 * @since 2023-12-13
 */
@Slf4j
@Service
public class SteadyStateMeteService extends ServiceImpl<SteadyStateMeteMapper, SteadyStateMete> {

    @Transactional(rollbackFor = Exception.class)
    public void handleKafkaData(KafkaMeteData meteData) {
        log.info("开始处理kafka过来的稳态类型测点数据：{}", meteData);
        SteadyStateMete stateMete = getByMeteCode(meteData.getMeteCode());
        if (stateMete == null) {
            log.info("处理结果：未找到稳态类型测点【{}】的数据", meteData.getMeteCode());
            log.info("处理kafka过来的稳态类型测点【{}】数据结束", meteData.getMeteCode());
            return;
        }
        SteadyStateMete newStateMete = new SteadyStateMete();
        newStateMete.setId(stateMete.getId());

        Integer kafkaDataVal = Integer.valueOf(meteData.getValue());
        Integer steadyStatus = stateMete.getSteadyStatus();
        Integer validMeteValue = stateMete.getValidMeteValue();
        //1.当meteData的值==validMeteValue时，判断状态是0和1的修改start_time
        //2.当meteData的值!=validMeteValue时，判断状态是1的修改end_time，同时状态改为2
        //其他情况不做处理
        log.info("准备处理kafka的data，kafkaDataVal:{}, validMeteValue:{}, steadyStatus:{}",
                kafkaDataVal, validMeteValue, steadyStatus);
        boolean changedFlag = false;
        if (validMeteValue.equals(kafkaDataVal)) {
            //注意endTime因为字段设置了FieldStrategy.IGNORED，不赋值时数据库中的值会遍为空
            newStateMete.setStartTime(new Timestamp(meteData.getGenerateTime()));
            newStateMete.setSteadyStatus(SteadyExecStatusEnum.PROCESSING.getValue());
            changedFlag = true;
            log.info("触发稳态测点：{}测点的{}工况稳态开始，开始时间{}",
                    stateMete.getMeteCode(), stateMete.getSteadyDesc(), meteData.getGenerateDate());
        } else if (SteadyExecStatusEnum.PROCESSING.getValue().equals(steadyStatus)) {
            newStateMete.setEndTime(new Timestamp(meteData.getGenerateTime()));
            newStateMete.setSteadyStatus(SteadyExecStatusEnum.COMPLETE.getValue());
            changedFlag = true;
            log.info("触发稳态情况：{}测点的{}稳态结束，结束时间{}",
                    stateMete.getMeteCode(), stateMete.getSteadyDesc(), meteData.getGenerateDate());
        }
        if (changedFlag) {
            this.updateById(newStateMete);
            log.info("处理结果：修改测点【{}】的稳态数据完成，具体为：{}", meteData.getMeteCode(),
                    JSONObject.toJSONString(newStateMete));
        } else {
            log.info("处理结果：未处理稳态类型测点【{}】的数据，generateDate：{}",
                    meteData.getMeteCode(), meteData.getGenerateDate());
        }
        log.info("处理kafka过来的稳态类型测点【{}】数据结束", meteData.getMeteCode());
    }

    private SteadyStateMete getByMeteCode(String meteCode) {
        if (StringUtils.isBlank(meteCode)) {
            return null;
        }
        LambdaQueryWrapper<SteadyStateMete> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SteadyStateMete::getMeteCode, meteCode);
        return this.getOne(queryWrapper);
    }

    public SteadyStateMete getByStatusOfProcessing(String machineNo, Integer steadyType) {
        Assert.notBlank(machineNo, "机组编号不能为空");
        LambdaQueryWrapper<SteadyStateMete> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SteadyStateMete::getMachineNo, machineNo);
        queryWrapper.eq(SteadyStateMete::getSteadyStatus, SteadyExecStatusEnum.PROCESSING.getValue());
        queryWrapper.eq(SteadyStateMete::getSteadyType, steadyType);
        //担心有多个状态为1的数据，
        queryWrapper.orderByDesc(SteadyStateMete::getUpdateTime);
        List<SteadyStateMete> list = this.list(queryWrapper);
        log.info("稳态测点:{},稳态类型:{}", JSON.toJSONString(list), steadyType);
        return CollectionUtils.isEmpty(list) ? null : list.get(0);
    }

    public List<SteadyStateMete> getByMachineNo(String machineNo) {
        Assert.notBlank(machineNo, "机组编号不能为空");
        LambdaQueryWrapper<SteadyStateMete> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SteadyStateMete::getMachineNo, machineNo);
        queryWrapper.orderByDesc(SteadyStateMete::getUpdateTime);
        return this.list(queryWrapper);
    }

}